package com.demo.task.utils

import kotlin.math.*

class LocationUtils {
    private var previousLongitude: Double? = null
    private var previousLatitude: Double? = null

    // 记录位置信息并进行距离判断的函数
    fun getDistance(longitudeStr: String, latitudeStr: String): Double {
        // 校验输入是否合法
        val longitude = try {
            longitudeStr.toDouble()
        } catch (e: NumberFormatException) {
            throw IllegalArgumentException("Invalid longitude format: $longitudeStr")
        }
        val latitude = try {
            latitudeStr.toDouble()
        } catch (e: NumberFormatException) {
            throw IllegalArgumentException("Invalid latitude format: $latitudeStr")
        }

        return if (previousLongitude == null || previousLatitude == null) {
            // 第一次记录数据，没有距离可计算
            previousLongitude = longitude
            previousLatitude = latitude
            0.0
        } else {
            // 计算与上一次坐标的距离
            val distance = calculateDistance(
                previousLongitude!!,
                previousLatitude!!,
                longitude,
                latitude
            )
            // 更新上一次坐标
            previousLongitude = longitude
            previousLatitude = latitude
            distance
        }
    }

    // 计算两个经纬度之间的距离的函数
    private fun calculateDistance(
        lon1: Double,
        lat1: Double,
        lon2: Double,
        lat2: Double
    ): Double {
        val R = 6371e3  // 地球半径，单位为米
        val lat1Rad = Math.toRadians(lat1)
        val lat2Rad = Math.toRadians(lat2)
        val deltaLat = Math.toRadians(lat2 - lat1)
        val deltaLon = Math.toRadians(lon2 - lon1)

        val a = sin(deltaLat / 2).pow(2) + cos(lat1Rad) * cos(lat2Rad) * sin(deltaLon / 2).pow(2)
        val c = 2 * atan2(sqrt(a), sqrt(1 - a))
        return R * c
    }
}